<!--
 * @Description: 科室医生筛选
 * @Author BPF
 * @create 2021/11/30 15:44
 -->
<!--default-->
<script>
export default { name: 'filter-date-pro' }
</script>

<!--setup-->
<script setup>
import { computed, nextTick, onMounted, onUnmounted, reactive, watch, getCurrentInstance } from 'vue'
import dayjs from 'dayjs'
import { computedDays } from '/src/libs/utils/common'
const { proxy } = getCurrentInstance()
const _conf = {
  年: {
    label: '按年份',
    value: '年',
    list: [...new Array(new Date().getFullYear() - 2015 + 1)].map((v, vi) => ({
      value: 2015 + vi,
      label: `${2015 + vi}年`
    }))
  },
  季: {
    label: '按季度',
    value: '季',
    list: [
      { value: '1', label: '第一季度', months: [1, 2, 3] },
      { value: '2', label: '第二季度', months: [4, 5, 6] },
      { value: '3', label: '第三季度', months: [7, 8, 9] },
      { value: '4', label: '第四季度', months: [10, 11, 12] }
    ]
  },
  月: {
    label: '按月份',
    value: '月',
    list: [...new Array(12)].map((v, vi) => ({ value: `${vi + 1}`.padStart(2, '0'), label: `${vi + 1}月` }))
  },
  日: { label: '按日期', value: '日', list: [] }
}

const props = defineProps({
  dateTypes: {
    type: Array,
    default: () => ['年', '季', '月', '日']
  },
  value: {
    type: String,
    default: '日'
  }
})
const emit = defineEmits(['confirm', 'update:value'])
defineExpose({
  getDate
})
const state = reactive({
  dateLabel: '',
  visible: {
    dateType: false
  },
  dateColumns: []
})

const dateTypesCp = computed(() => props.dateTypes.map(v => _conf[v]))

watch(
  () => props.value,
  newVal => {
    handlerAllDate(newVal)
  }
)

onMounted(async () => {
  handlerAllDate(props.value)
  const { dateLabel } = await getDate()
  state.dateLabel = dateLabel
})

onUnmounted(() => {})

// @expose 获取日期
function getDate() {
  return new Promise(resolve => {
    nextTick(() => {
      let params = {}
      let dateLabel = ''
      switch (props.value) {
        case '年': {
          const [yIndex] = proxy.$refs.picker.getIndexes()
          const year = state.dateColumns[yIndex]?.value
          params = computedDays(props.value, `${year}-01-01`)
          dateLabel = `${year}年`
          break
        }
        case '季': {
          const [yIndex, qIndex] = proxy.$refs.picker.getIndexes()
          const year = state.dateColumns[yIndex]?.value
          const quarter = state.dateColumns[yIndex]?.children[qIndex]?.value
          const quarterLabel = state.dateColumns[yIndex]?.children[qIndex]?.text
          params = computedDays(props.value, `${year}-${quarter.slice().pop().toString().padStart(2, '0')}`)
          dateLabel = `${year}年${quarterLabel}`
          break
        }
        case '月': {
          const [yIndex, mIndex] = proxy.$refs.picker.getIndexes()
          const year = state.dateColumns[yIndex]?.value
          const month = state.dateColumns[yIndex]?.children[mIndex]?.value
          const monthLabel = state.dateColumns[yIndex]?.children[mIndex]?.text
          params = computedDays(props.value, `${year}-${month}`)
          dateLabel = `${year}年${monthLabel}`
          break
        }
        case '日': {
          const [yIndex, mIndex, dIndex] = proxy.$refs.picker.getIndexes()
          const year = state.dateColumns[yIndex]?.value
          const month = state.dateColumns[yIndex]?.children[mIndex]?.value
          const day = state.dateColumns[yIndex]?.children[mIndex]?.children[dIndex]?.value
          params = computedDays(props.value, dayjs(`${year}-${month}-${day}`).add(1, 'day').format('YYYY-MM-DD'))
          dateLabel = `${year}年${month}月${day}日`
          break
        }
      }
      resolve({
        ...params,
        dateLabel
      })
    })
  })
}

/**
 * 确认
 */
async function onConfirmDateType() {
  const params = await getDate()
  state.dateLabel = params.dateLabel
  state.visible.dateType = false
  emit('confirm', params)
}

/**
 * 选择日期类别
 * @param val
 */
function onChooseDateType(val) {
  emit('update:value', val.value)
}

/**
 *处理所有日期
 * @param date
 */
function handlerAllDate(date = '日') {
  const handlersFn = {
    年: handleYear.bind(null),
    季: handleQuarter.bind(null),
    月: handlerMonth.bind(null),
    日: handlerDay.bind(null)
  }
  date ? handlersFn[date]?.() : (state.dateColumns = [])
}

/**
 * 处理年
 */
function handleYear() {
  nextTick(() => {
    proxy.$refs.picker && proxy.$refs.picker.setIndexes([_conf.年.list.length - 1])
  })
  state.dateColumns = _conf.年.list.map(v => {
    return {
      text: v.label,
      value: v.value
    }
  })
}

/**
 * 处理月
 */
function handlerMonth() {
  const year = new Date().getFullYear()
  const curMonth = new Date().getMonth() + 1
  nextTick(() => {
    proxy.$refs.picker && proxy.$refs.picker.setIndexes([_conf.年.list.length - 1, curMonth - 1])
  })
  state.dateColumns = _conf.年.list.map(v => {
    return {
      text: v.label,
      value: v.value,
      children: _conf.月.list.map(o => {
        return {
          text: o.label,
          value: o.value,
          disabled: +v.value >= year && o.value > curMonth - 1
        }
      })
    }
  })
}

/**
 * 处理季
 */
function handleQuarter() {
  const year = new Date().getFullYear()
  const quarterIndex = _conf.季.list.findIndex(v => {
    return v.months.includes(Number(new Date().getMonth() + 1))
  })
  nextTick(() => {
    proxy.$refs.picker && proxy.$refs.picker.setIndexes([_conf.年.list.length - 1, quarterIndex || 0])
  })
  state.dateColumns = _conf.年.list.map(v => {
    return {
      text: v.label,
      value: v.value,
      children: _conf.季.list.map((o, oi) => {
        return {
          text: o.label,
          value: o.months,
          disabled: +v.value >= year && oi > quarterIndex - 1
        }
      })
    }
  })
}

/**
 * 处理日
 */
function handlerDay() {
  const date = new Date()
  const curYear = date.getFullYear()
  const curMonth = date.getMonth() + 1
  const curDay = date.getDate()
  nextTick(() => {
    proxy.$refs.picker && proxy.$refs.picker.setIndexes([_conf.年.list.length - 1, curMonth - 1, curDay - 1])
  })
  state.dateColumns = _conf.年.list.map(v => {
    return {
      text: v.label,
      value: v.value,
      disabled: +v.value > curYear,
      children: _conf.月.list.map(o => {
        return {
          text: o.label,
          value: o.value,
          disabled: +v.value >= curYear && o.value > curMonth,
          children: [...new Array(Number(dayjs(`${v.value}-${o.value}`).daysInMonth()))].map((k, ki) => {
            return {
              text: `${ki + 1}日`,
              value: `${ki + 1}`.padStart(2, '0'),
              disabled:
                +v.value >= curYear &&
                o.value >= curMonth &&
                Number(`${o.value.toString().padStart(2, '0')}${ki.toString().padStart(2, '0')}`) >
                  Number(`${curMonth.toString().padStart(2, '0')}${(curDay - 2).toString().padStart(2, '0')}`)
            }
          })
        }
      })
    }
  })
}
</script>

<!--render-->
<template>
  <div class="filter-date-pro">
    <div class="filter__wrap">
      <div class="filter__item" @click="state.visible.dateType = true">
        <span :class="[state.dateLabel && 'filter__item--active']">{{
          state.dateLabel ? state.dateLabel : '选择日期'
        }}</span>
        <i class="iconfont-bpf-m icon-m-xiangxia1"></i>
      </div>
    </div>

    <van-popup v-model:show="state.visible.dateType" position="bottom" :lazy-render="false" get-container="body">
      <div class="popup-body">
        <div class="top-header">
          <div @click="state.visible.dateType = false">取消</div>
          <div @click="onConfirmDateType">确定</div>
        </div>
        <div class="date-type">
          <div
            v-for="(item, index) in dateTypesCp"
            :key="index"
            :class="['date-type__item', value == item.value && 'date-type__item--active']"
            @click="onChooseDateType(item)"
          >
            {{ item.label }}
          </div>
        </div>
        <van-picker ref="picker" :show-toolbar="false" :columns="state.dateColumns" :visible-item-count="7" />
      </div>
    </van-popup>
  </div>
</template>

<!--style-->
<style scoped lang="less">
@import './index.less';
</style>
